package com.baolai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baolai.dto.Device;
import com.baolai.entity.GoodsDevice;
import com.baolai.mapper.GoodsDeviceMapper;
import com.baolai.service.GoodsDeviceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsDeviceServiceImpl extends ServiceImpl<GoodsDeviceMapper, GoodsDevice> implements GoodsDeviceService {

    @Autowired
    GoodsDeviceMapper goodsDeviceMapper;

    @Override
    public JSONObject listDevice(String key, Integer current, Integer size) {
        JSONObject jsonObject = new JSONObject();
        Integer count = goodsDeviceMapper.countDevice();
        Integer pages = (int) Math.ceil(count/size);
        jsonObject.put("total",count);
        jsonObject.put("pages",pages);
        if(key.length() > 0){
            jsonObject.put("records",goodsDeviceMapper.listDeviceByName(key,(current-1)*size,size));
            return jsonObject;
        }else{
            List<Device> devices = goodsDeviceMapper.listDevice((current-1)*size,size);
            jsonObject.put("records",devices);
            return jsonObject;
        }
    }

    @Override
    public boolean addGoodsDevice(GoodsDevice goodsDevice) {
        GoodsDevice goodsDevice1 = this.getGoodsDevice(goodsDevice.getGoodsId(),goodsDevice.getDeviceId());
        if(goodsDevice1 != null){
            UpdateWrapper<GoodsDevice> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("goods_id",goodsDevice.getGoodsId()).eq("device_id",goodsDevice.getDeviceId());
            return this.update(goodsDevice,updateWrapper);
        }
        return this.save(goodsDevice);
    }

    @Override
    public boolean deleteGoodsDevice(String goodsId, String deviceId) {
        QueryWrapper<GoodsDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId).eq("device_id",deviceId);
        return this.remove(queryWrapper);
    }

    @Override
    public GoodsDevice getGoodsDevice(String goodsId, String deviceId) {
        QueryWrapper<GoodsDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId).eq("device_id",deviceId);
        return this.getOne(queryWrapper);
    }

    @Override
    public IPage<GoodsDevice> listGoodsDeviceByGoodsId(String goodsId, Integer current, Integer size) {
        QueryWrapper<GoodsDevice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",goodsId);
        IPage<GoodsDevice> page = new Page<>(current,size);
        return this.page(page,queryWrapper);
    }
}
